package com.db.service.email;

import java.io.Serializable;

public class EmailService {

    private final EmailQueue queue = new EmailQueue();
    Thread emailSender;

    public EmailService() {
        emailSender = new EmailSender("Email sender");
    }

    public void start() {
        emailSender.start();
    }
    public boolean sendNotificationEmail(Email email) {
        return queue.add(email);
    }

    public void close() {
        queue.setCanAddInQueue(false);
        emailSender.interrupt();
    }

    private class EmailSender extends Thread implements Serializable {
        private EmailSender(String name) {
            super(name);
        }

        @Override
        public void run() {
            Email email;
            while((email = queue.remove()) != null) {
                System.out.println("Email: " + email.getClient().getClientSalutation() + " : " + email.getEmail());
            }
            System.out.println("thread is dead");
        }
    }
}
